// Background script for the extension

// Initialize IndexedDB
let db;
const dbRequest = indexedDB.open("XiaohongshuSearchDB", 1);

dbRequest.onupgradeneeded = function(event) {
  db = event.target.result;
  if (!db.objectStoreNames.contains("searchResults")) {
    const store = db.createObjectStore("searchResults", { keyPath: "id", autoIncrement: true });
    store.createIndex("query", "query", { unique: false });
    store.createIndex("timestamp", "timestamp", { unique: false });
  }
};

dbRequest.onsuccess = function(event) {
  db = event.target.result;
  console.log("Background script: IndexedDB initialized successfully");
};

dbRequest.onerror = function(event) {
  console.error("Background script: Error initializing IndexedDB:", event.target.error);
};

chrome.runtime.onInstalled.addListener(() => {
  console.log('Xiaohongshu Search Export Tool installed');
});

// Listen for messages from content script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "saveSearchData") {
    console.log("Background: Received search data to save", message);
    
    // Save items to IndexedDB
    if (message.items && message.items.length > 0) {
      saveItemsToDb(message.items, message.query, message.url);
    }
    
    // Update badge to show that new data is available
    chrome.action.setBadgeText({ text: "新" });
    chrome.action.setBadgeBackgroundColor({ color: "#FF2442" }); // Xiaohongshu red
    
    console.log(`New search data saved: ${message.query} at ${message.timestamp}`);
  } else if (message.action === "newDataSaved") {
    // For backward compatibility
    chrome.action.setBadgeText({ text: "新" });
    chrome.action.setBadgeBackgroundColor({ color: "#FF2442" });
  }
  
  return true; // Required for async response
});

// Function to save items to IndexedDB
function saveItemsToDb(items, query, url) {
  if (!db) {
    console.error("Database not initialized yet");
    return;
  }
  
  const transaction = db.transaction(["searchResults"], "readwrite");
  const store = transaction.objectStore("searchResults");
  
  items.forEach(item => {
    const record = {
      query: query,
      data: item,
      timestamp: new Date().toISOString(),
      url: url
    };
    
    const request = store.add(record);
    
    request.onsuccess = function() {
      console.log("Background script: Item saved to IndexedDB");
    };
    
    request.onerror = function(event) {
      console.error("Background script: Error saving to IndexedDB:", event.target.error);
    };
  });
  
  transaction.oncomplete = function() {
    console.log(`Saved ${items.length} items for query "${query}"`);
  };
}

// Clear badge when popup is opened
chrome.action.onClicked.addListener((tab) => {
  chrome.action.setBadgeText({ text: "" });
}); 